//
//  BMSInitializer.m
//  WDBMS
//
//  Created by YeJary on 2025/5/13.
//

#import "BMSInitializer.h"
#import "BMSAPIService.h"
#import "BMSPrivate.h"
#import "BMSDeviceInfo.h"
#import "BMSOpMergeReporter.h"
#import "BMSPermissionManager.h"
#import "BMSAppInfoHelper.h"
#import "BMSDataPersistenceManager.h"
#import "BMSPrivate.h"
#import "BMSKeychain.h"

@interface BMSInitializer ()

@property (nonatomic, assign) BOOL didAgreePrivacy;
@property (nonatomic, assign) BOOL didRealnameAuth;
@property (nonatomic, assign) BOOL idfaAuthorized;
//@property (nonatomic, assign) BOOL isTeenager;
@property (nonatomic, assign) BOOL didLogin;
@property (nonatomic, assign) BOOL shouldShowAntiAddictionTip;
@property (nonatomic, assign) BOOL shouldForceLogout;
@property (nonatomic, strong) NSArray<NSString *> *holidayList;
@property (nonatomic, strong) NSDate *serverNowDate;

@property (nonatomic,strong)BMSLoginResponseModel *loginModel;

@property (nonatomic,strong) BMSLaunchConfigModel *launchModel;

@property (nonatomic, copy) NSString *uuid;

@end

@implementation BMSInitializer

- (instancetype)init {
    self = [super init];
    if (self) {
        [self loadCachedState];//刷新缓存
    }
    return self;
}

+ (instancetype)shared {
    static BMSInitializer *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[BMSInitializer alloc] init];
        [instance loadCachedState];
#ifdef DEBUG
//        [instance clearCachedStateForTesting];
#endif
    });
    return instance;
}

- (void)loadCachedState {
    NSUserDefaults *ud = NSUserDefaults.standardUserDefaults;
    self.didAgreePrivacy = [ud boolForKey:kBMSKeyPrivacyAgreed];
    self.didRealnameAuth = [ud boolForKey:kBMSKeyRealnameAuth];
    self.isTeenager = [ud boolForKey:kBMSKeyIsTeenager];

    NSArray *cachedHolidays = [ud objectForKey:kBMSKeyHolidayList];
    
    NSDate *cacheDate = [ud objectForKey:kBMSKeyHolidayCacheDate];
    if (cachedHolidays && [cacheDate isKindOfClass:NSDate.class]) {
        NSTimeInterval delta = [[NSDate date] timeIntervalSinceDate:cacheDate];
        if (delta < 24 * 60 * 60) {
            self.holidayList = cachedHolidays;
        }
    }
}

- (void)clearCachedStateForTesting {
    NSUserDefaults *ud = NSUserDefaults.standardUserDefaults;
    
    [ud removeObjectForKey:kBMSKeyPrivacyAgreed];
    [ud removeObjectForKey:kBMSKeyRealnameAuth];
    [ud removeObjectForKey:kBMSKeyIsTeenager];
    [ud removeObjectForKey:kBMSKeyHolidayList];
    [ud removeObjectForKey:kBMSKeyHolidayCacheDate];
    
    [ud synchronize];
    
    self.didAgreePrivacy = NO;
    self.didRealnameAuth = NO;
    self.isTeenager = NO;
    self.holidayList = @[];
    
    NSLog(@"[BMS] 测试清除缓存已执行");
}

+ (void)startWithAppName:(NSString *)appName
                 version:(NSString *)version
                 channel:(NSString *)channel
              completion:(void(^)(void))completion {

    BMSInitializer *mgr = [BMSInitializer shared];
    dispatch_group_t group = dispatch_group_create();

    void (^retryBlock)(dispatch_block_t block, NSInteger maxRetry) = ^(dispatch_block_t block, NSInteger maxRetry) {
        __block NSInteger retry = 0;
        void (^attempt)(void) = ^{ block(); };
        void (^retryHandler)(void) = ^{
            retry++;
            if (retry < maxRetry) {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), attempt);
            } else {
                attempt();
            }
        };
        attempt();
    };

    dispatch_group_enter(group);
    retryBlock(^{
        [BMSAPIService fetchGameLaunchConfigWithVersion:version appName:appName success:^(id responseObject) {
            int code = [[responseObject objectForKey:@"code"]intValue];
            if (code == 0){
                NSDictionary *responseData = responseObject[@"data"];
                BMSLaunchConfigModel *model = [BMSLaunchConfigModel modelWithDictionary:responseData];
                [BMSInitializer shared].launchModel = model;
                [[BMSOpMergeReporter shared]setupWithLaunchConfig:model];
                
                [BMSOpMergeEventBuilder event_userOpWithAct:BMS_EVENT_BASE_JSON description:BMS_WDS_FETCH_CONFIG];
                
                NSLog(@"获取启动配置成功------------%@",responseObject);
            } else {
                NSLog(@"获取启动配置失败————————————%@",responseObject);
            }
            
            dispatch_group_leave(group);
        } failure:^(NSError *error) {
            dispatch_group_leave(group);
        }];
    }, 5);

    if (!mgr.holidayList) {
        dispatch_group_enter(group);
        retryBlock(^{
            [BMSAPIService fetchOfficialHolidaysWithSuccess:^(id  _Nonnull responseObject) {
                int code = [[responseObject objectForKey:@"code"]intValue];
                if (code == 0) {
                    BMSOfficialHolidayModel *model = [BMSOfficialHolidayModel modelWithRawArray:responseObject[@"data"]];
                    mgr.holidayList = model.holidayList;
                    [BMSAntiAddictionManager shared].holidaySet = model.holidayList;
                    NSUserDefaults *ud = NSUserDefaults.standardUserDefaults;
                    [ud setObject:model.holidayList forKey:kBMSKeyHolidayList];
                    [ud setObject:[NSDate date] forKey:kBMSKeyHolidayCacheDate];
                    NSLog(@"获取国家法定节假日成功!!!!!!!!!!%@",responseObject);
                } else {
                    NSLog(@"获取国家法定节假日失败!!!!!!!!!!%@",responseObject);
                }
                
                dispatch_group_leave(group);
            } failure:^(NSError * _Nonnull error) {
                dispatch_group_leave(group);
            }];
        }, 5);
    }

    dispatch_group_enter(group);
    retryBlock(^{
        [BMSAPIService checkIPBlockStatusWithAppName:appName channel:channel version:version ip:nil success:^(NSDictionary *response) {
            int code = [[response objectForKey:@"code"]intValue];
            if (code == 0){
                NSDictionary *data = response[@"data"];
                BMSIPBlockStatusModel *model = [BMSIPBlockStatusModel modelWithDictionary:data];
                mgr.serverNowDate = [NSDate date];
                NSLog(@"获取IP 屏蔽成功！！！！！！！%@",response);
            } else {
                NSLog(@"获取 IP 屏蔽失败！！！!!!！%@",response);
            }
            
            dispatch_group_leave(group);
        } failure:^(NSError *error) {
            dispatch_group_leave(group);
        }];
    }, 5);

    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        [mgr evaluateAntiAddictionPolicy];
        if (completion) completion();
    });
}

- (void)markPrivacyAgreed {
    self.didAgreePrivacy = YES;
    [NSUserDefaults.standardUserDefaults setBool:YES forKey:kBMSKeyPrivacyAgreed];
}

- (void)markRealnameVerified:(BOOL)isTeenager {
    self.didRealnameAuth = YES;
    self.isTeenager = isTeenager;
    NSUserDefaults *ud = NSUserDefaults.standardUserDefaults;
    [ud setBool:YES forKey:kBMSKeyRealnameAuth];
    [ud setBool:isTeenager forKey:kBMSKeyIsTeenager];
}

- (void)evaluateAntiAddictionPolicy {
    if (!self.isTeenager) {
        self.shouldShowAntiAddictionTip = NO;
        self.shouldForceLogout = NO;
        return;
    }

    NSDate *now = self.serverNowDate ?: [NSDate date];
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    df.dateFormat = @"yyyyMMdd";
    NSString *dateKey = [df stringFromDate:now];
    BOOL isHoliday = [self.holidayList containsObject:dateKey];

    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSInteger weekday = [calendar component:NSCalendarUnitWeekday fromDate:now];
    BOOL isWeekend = (weekday == 1 || weekday == 7 || weekday == 6);

    if (!(isHoliday || isWeekend)) {
        self.shouldShowAntiAddictionTip = YES;
        self.shouldForceLogout = YES;
        return;
    }

    NSDateComponents *components = [calendar components:NSCalendarUnitHour | NSCalendarUnitMinute fromDate:now];
    NSInteger hour = components.hour;
    NSInteger minute = components.minute;
    if (hour != 20 || (minute < 0 || minute >= 60)) {
        self.shouldShowAntiAddictionTip = YES;
        self.shouldForceLogout = YES;
    } else {
        self.shouldShowAntiAddictionTip = NO;
        self.shouldForceLogout = NO;
    }
}

- (void)handlePrivacyAgreedAndLoginWithCompletion:(void(^)(BOOL loginSuccess))completion {
    // 标记已同意隐私
    self.didAgreePrivacy = YES;

    // 获取 IDFA、IDFV
    [[BMSPermissionManager sharedManager] fetchIdentifiersWithCompletion:^(NSString * _Nullable idfa, NSString *idfv) {
        self.idfaAuthorized = (idfa.length > 0);

        // 更新设备信息
        [[BMSDeviceInfo shared] updateWithIDFA:idfa idfv:idfv];

        // 请求登录（可用缓存 UUID 或新建）
        [BMSAPIService loginWithOpenId:[BMSAppInfoHelper getOpenId]
                               appName:[BMSAppInfoHelper bmsAppNameForInfoPlistFile]
                             platform:@"ios"
                                 idfa:idfa
                                 idfv:idfv
                                 imei:nil
                                 oaid:nil
                                 adid:nil
                                  mac:nil
                               serial:nil
                              success:^(NSDictionary *response) {
            NSLog(@"登录完成: %@", response);
            
            int code = [response[@"code"]intValue];;
            if(code == 0) {
                NSDictionary *data = response[@"data"];
                BMSLoginResponseModel *model = [BMSLoginResponseModel modelWithDictionary:data];
                self.loginModel = model;
                [self handleUserSourceInfo];
                self.loginModel = [[BMSLoginResponseModel alloc] init];
                self.uuid = model.uuid;
                self.didLogin = YES;
                if (completion) completion(YES);
            } else {
                NSLog(@"登录失败\n%@",response);
                self.didLogin = NO;
                self.uuid = [BMSKeychain WDKeychainGetUUID];
                if (completion) completion(NO);
            }
            
        } failure:^(NSError *error) {
            self.didLogin = NO;
            self.uuid = [BMSKeychain WDKeychainGetUUID];
            if (completion) completion(NO);
            NSLog(@"登录失败: %@", error.localizedDescription);
        }];
    }];
}

- (void)handlePrivacyAgreedAndLogin {
    [[BMSInitializer shared] markPrivacyAgreed];

    NSString *userId = [BMSKeychain WDKeychainGetUUID];
    NSString *idfa = [BMSDeviceInfo shared].idfa;
    NSString *idfv = [BMSDeviceInfo shared].idfv;
    
    [BMSInitializer shared].appName = [BMSAppInfoHelper bmsAppNameForInfoPlistFile];

    [BMSAPIService loginWithOpenId:userId
                           appName:[BMSInitializer shared].appName
                         platform:@"ios"
                             idfa:idfa
                             idfv:idfv
                             imei:nil
                             oaid:nil
                             adid:nil
                              mac:nil
                           serial:nil
                          success:^(NSDictionary *response) {
        NSLog(@"登录完成: %@", response);
        
        [[BMSOpMergeReporter shared]addEvent:[BMSOpMergeEventBuilder event_userActionWithAct:BMS_EVENT_USER_LOGIN description:BMS_WDS_ACTIVE_STATISTICS tab1:@"" tab2:@"" tab3:@"" tabN:@{}]];
        
        
        int code = [response[@"code"]intValue];;
        if(code == 0) {
            NSDictionary *data = response[@"data"];
            BMSLoginResponseModel *model = [BMSLoginResponseModel modelWithDictionary:data];
            self.loginModel = model;
            [self handleUserSourceInfo];
        } else {
            NSLog(@"登录失败\n%@",response);
        }
        
    } failure:^(NSError *error) {
        NSLog(@"登录失败: %@", error.localizedDescription);
    }];
}

- (void)handleUserSourceInfo {
    NSString *idfa = [BMSDeviceInfo shared].idfa;
    NSString *idfv = [BMSDeviceInfo shared].idfv;
    [BMSAPIService fetchUserSourceWithAppName:@"your_app"
                                      version:@"1.0.0"
                                      channel:@"weixin"
                                         uuid:self.uuid
                                         idfa:idfa
                                         idfv:idfv
                                         imei:nil
                                         oaid:nil
                                   android_id:nil
                                      success:^(NSDictionary *sourceData) {
        int code = [[sourceData objectForKey:@"code"]intValue];
        if (code == 0){
            NSLog(@"✅ 用户来源：%@", sourceData);
        } else {
            NSLog(@"获取用户来源失败\n %@",sourceData);
        }
        
    } failure:^(NSError *error) {
        NSLog(@"❌ 获取用户来源失败：%@", error.localizedDescription);
    }];
}


#pragma mark ------- lazy load --------

- (BMSLoginResponseModel *)loginModel {
    if (!_loginModel) {
        _loginModel = [[BMSLoginResponseModel alloc] init];
    }
    return _loginModel;
}

- (BMSLaunchConfigModel *)launchModel {
    if(!_launchModel){
        _launchModel = [[BMSLaunchConfigModel alloc]init];
    }
    return _launchModel;
}

@end
